﻿'Copyright (c) 2009 Grailtek

'Permission is hereby granted, free of charge, to any person
'obtaining a copy of this software and associated documentation
'files (the "Software"), to deal in the Software without
'restriction, including without limitation the rights to use,
'copy, modify, merge, publish, distribute, sublicense, and/or sell
'copies of the Software, and to permit persons to whom the
'Software is furnished to do so, subject to the following
'conditions:

'The above copyright notice and this permission notice shall be
'included in all copies or substantial portions of the Software.

'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
'EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
'OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
'NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
'HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
'WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
'FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
'OTHER DEALINGS IN THE SOFTWARE.

Imports System.Reflection
Imports System.Reflection.Emit

'NOTE: created types will cause ImplementorFactory to barf if any implented interfaces are not public
Public Interface IFactoryCreatedImplementor
End Interface

Friend NotInheritable Class InterfaceImplementor(Of T)

    Private Sub New()
    End Sub

    Public Shared ReadOnly MaterializedType As Type = InterfaceImplementor.GetMaterializedType(GetType(T))

End Class

Friend NotInheritable Class InterfaceImplementor

    'Public Const KeyFileName As String = "System.ExecutorServices.pfx"

    ''TODO: this needs to be an .snk file, will probably be the last thing to go in here
    'Private Shared Function GetKeyPair() As Byte()
    '    Dim keyPair(-1) As Byte
    '    Using s As IO.Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("System." & KeyFileName)
    '        'If stream Is Nothing Then Throw New MissingManifestResourceException("Failed to locate file System.ExecutorServices.snk required to sign generated assembly.")
    '        If s Is Nothing Then Debug.Fail(String.Format("Failed to locate file {0} required to sign generated assembly.", KeyFileName))
    '        Dim length As Integer = CInt(s.Length)
    '        ReDim keyPair(length)
    '        s.Read(keyPair, 0, length)
    '    End Using
    '    Return keyPair
    'End Function

    Private Shared ReadOnly propAtr As MethodAttributes = MethodAttributes.Public Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig Or MethodAttributes.Virtual
    Private Shared ReadOnly appDomain As AppDomain = System.Threading.Thread.GetDomain()
    Private Shared ReadOnly assemblyName As New AssemblyName("InterfaceImplementorFactoryAssembly") 'With {.KeyPair = New StrongNameKeyPair(GetKeyPair)}
    Private Shared ReadOnly assemblyBuilder As AssemblyBuilder = appDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run)
    Private Shared ReadOnly moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("InterfaceImplementorFactoryModule")
    Private Shared ReadOnly serializableAtr As CustomAttributeBuilder = CustomAttributeUtil.CreateCustomAttribute(New SerializableAttribute)

    Public Const ConstructedTypePrefix As String = "System.ExecutorServices.__"

    Public Shared Function GetMaterializedType(ByVal interfaceType As Type) As Type

        Dim ret As Type = Nothing

        If interfaceType.IsInterface Then

            Dim typeBuilder As TypeBuilder = moduleBuilder.DefineType(ConstructedTypePrefix & interfaceType.FullName.Replace("+", ".").Replace("\", ""), TypeAttributes.[Class] Or TypeAttributes.[Public])
            typeBuilder.AddInterfaceImplementation(interfaceType)
            typeBuilder.AddInterfaceImplementation(GetType(IFactoryCreatedImplementor))

            Dim ctorBuilder As ConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.[Public], CallingConventions.Standard, Type.EmptyTypes)
            Dim ilGenerator As ILGenerator = ctorBuilder.GetILGenerator()
            ilGenerator.Emit(OpCodes.Ldarg_0)
            ilGenerator.Emit(OpCodes.[Call], objCtor)
            ilGenerator.Emit(OpCodes.Ret)

            'NOTE: type generation tolerates duplicate names in properties and methods that can come from mulitple interface inheritance,
            ' this is not a good thing, though; but we can't throw exceptions here because they can cause confusing TypeLoadExceptions to
            ' be thrown when statically declared fields use this method indirectly from Aspect(Of )
            Dim methods As List(Of MethodInfo) = GetMethods(interfaceType)
            Dim properties As PropertyInfo() = GetProperties(interfaceType)

            Dim propDupsDetector As New Dictionary(Of String, PropertyInfo)

            For Each p As PropertyInfo In properties

                If propDupsDetector.ContainsKey(p.Name) Then
                    Dim otherProp As PropertyInfo = propDupsDetector(p.Name)
                    'NOTE: this is really important, will reduce a number of WTF moments as developers will invevitably create this hard-to-spot condition
                    Dim msg As String = "'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}' for '{3}'"
                    Debug.Fail(String.Format(msg, p.Name, p.DeclaringType.Name, otherProp.DeclaringType.Name, interfaceType.Name))
                Else
                    propDupsDetector.Add(p.Name, p)
                End If

                Dim propBuilder As PropertyBuilder = typeBuilder.DefineProperty(p.Name, PropertyAttributes.None, p.PropertyType, Nothing)
                Dim field As FieldBuilder = typeBuilder.DefineField("_" & p.Name, p.PropertyType, FieldAttributes.[Private])

                Dim getMethod As MethodInfo = p.GetGetMethod()
                If Not getMethod Is Nothing Then
                    methods.Remove(getMethod) 'getters and setters are methods, need to be removed from the general methods list
                    Dim getMethodBuilder As MethodBuilder = typeBuilder.DefineMethod(getMethod.Name, propAtr, p.PropertyType, Type.EmptyTypes)
                    ilGenerator = getMethodBuilder.GetILGenerator()
                    ilGenerator.Emit(OpCodes.Ldarg_0)
                    ilGenerator.Emit(OpCodes.Ldfld, field)
                    ilGenerator.Emit(OpCodes.Ret)
                    typeBuilder.DefineMethodOverride(getMethodBuilder, getMethod)
                    propBuilder.SetGetMethod(getMethodBuilder)
                End If

                Dim setMethod As MethodInfo = p.GetSetMethod()
                If Not setMethod Is Nothing Then
                    methods.Remove(setMethod) 'getters and setters are methods, need to be removed from the general methods list
                    Dim setMethodBuilder As MethodBuilder = typeBuilder.DefineMethod(setMethod.Name, propAtr, Nothing, New Type() {p.PropertyType})
                    ilGenerator = setMethodBuilder.GetILGenerator()
                    ilGenerator.Emit(OpCodes.Ldarg_0)
                    ilGenerator.Emit(OpCodes.Ldarg_1)
                    ilGenerator.Emit(OpCodes.Stfld, field)
                    ilGenerator.Emit(OpCodes.Ret)
                    typeBuilder.DefineMethodOverride(setMethodBuilder, setMethod)
                    propBuilder.SetSetMethod(setMethodBuilder)
                End If

            Next

            Dim methodDupsDetector As New Dictionary(Of String, MethodInfo)

            For Each m As MethodInfo In methods

                If methodDupsDetector.ContainsKey(m.Name) Then
                    Dim otherProp As PropertyInfo = propDupsDetector(m.Name)
                    'NOTE: this is really important, will reduce a number of WTF moments as developers will invevitably create this hard to spot condition
                    Dim msg As String = "'{0}' is ambiguous across the inherited interfaces '{1}' and '{2}' for '{3}'"
                    Debug.Fail(String.Format(msg, m.Name, m.DeclaringType.Name, otherProp.DeclaringType.Name, interfaceType.Name))
                Else
                    methodDupsDetector.Add(m.Name, m)
                End If

                Dim returnType As Type = m.ReturnType
                Dim argumentTypes As New List(Of Type)()
                For Each parameterInfo As ParameterInfo In m.GetParameters()
                    argumentTypes.Add(parameterInfo.ParameterType)
                Next
                Dim methodBuilder As MethodBuilder = typeBuilder.DefineMethod(m.Name, MethodAttributes.[Public] Or MethodAttributes.Virtual, returnType, argumentTypes.ToArray())
                ilGenerator = methodBuilder.GetILGenerator()
                If Not returnType Is GetType(Void) Then
                    Dim localBuilder As LocalBuilder = ilGenerator.DeclareLocal(returnType)
                    ilGenerator.Emit(OpCodes.Ldloc, localBuilder)
                End If
                ilGenerator.Emit(OpCodes.Ret)
                typeBuilder.DefineMethodOverride(methodBuilder, m)

            Next

            'while we're here, mark the type as serializable to maximize its utility
            typeBuilder.SetCustomAttribute(serializableAtr)

            ret = typeBuilder.CreateType()

        End If

        Trace.WriteLine(String.Format("Created Type {0}", ret.FullName))

        Return ret

    End Function

End Class
